<template>
  <div >
    <q-uploader
      ref="myRef"
      :url="fileUrl"
      field-name="files"
      max-files="1"
      :max-file-size="fileSize"
      multiple
      :accept="fileType"
      @failed="fileFailed"
      @uploaded="fileUploaded"
      :factory="uploadFile"
      :style="{'width': widthStyle + 'px'}"
    />
  </div>
</template>

<script lang="ts">
import { QUploader } from 'quasar';
import { defineComponent, ref, toRefs } from 'vue';


export default defineComponent({
  name: 'AmyImageUpload',
  props: {
    fileUrl: {
      type: String,
      required: true
    },

    fileType: {
      type: String,
      default: () => {
        return '.gif,.jpg,.jpeg,.png, .image/*'
      }
    },

    fileSize: {
      type: Number,
      default: () => {
        return 10240000
      }
    },

    widthStyle: {
      type: Number,
      default: () => {
        return 320
      }
    }
  },
  setup (props, context) {
    //数据解构
    const {
      fileUrl,
      fileType,
      fileSize,
      widthStyle
    } = toRefs(props);

    //Quploader
    let myRef = ref<QUploader | null>(null);

    //校验
    const filterFile = (files: File[]) => {

    }

    //上传成功
    const fileUploaded = (info: any) => {
      let files = info.files;
      let res = JSON.parse(info.xhr.response);
      //console.log(files);
      if (res.code === 200) {
        files.forEach((item: File) => {
          context.emit('file-upload', res.data[0]);
        });
        //console.log(res.code);
      }
    }

    //上传工厂函数
    const uploadFile = (files: File[]) => {
      return new Promise((resolve, reject) => {
        resolve('files');
      });
    }

    //上传失败
    const fileFailed = (info: any) => {

    }

    return {
      fileUrl,
      fileType,
      fileSize,
      widthStyle,
      myRef,
      filterFile,
      fileFailed,
      uploadFile,
      fileUploaded
    }
  }
})
</script>

<style lang="scss" scoped>


</style>
